package org.deng.java.JUC.procus;

/**
 * packageName org.deng.java.JUC.procus
 *
 *  线程--生产者与消费者问题
 *  通过一个信号量num来实现生产者和消费者的交替执行
 *  A-- num+1 --生产者
 *  B-- num-1 --消费者
 * @author dengjinzhang
 * @version JDK 1.8
 * @date 2024/9/29
 * @description TODO
 */
public class ProductAndCustomer {

    public static void main(String[] args) {
        Signal signal = new Signal();
        new Thread(()->{
            try {
                for (int i=0; i<10;i++) {
                    signal.increment();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) signal.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "B").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) signal.increment();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "C").start();

        new Thread(()->{
            try {
                for (int i = 0; i < 10; i++) signal.decrement();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "D").start();
    }
}

class Signal {

    //信号参数
    private int num = 0;

    // 生产者 执行num++操作
    public synchronized void increment() throws InterruptedException {
        while (num != 0) {
            this.wait();
        }
        num++;
        System.out.println(Thread.currentThread().getName() + " => " + num);
        this.notifyAll();
    }
    //消费者 执行num--操作
    public synchronized void decrement() throws InterruptedException {
        while (num == 0){
            this.wait();
        }
        num--;
        System.out.println(Thread.currentThread().getName()+" =>" + num);
        this.notifyAll();
    }
}
